// src/utils/webrtcClient.js
let localStream = null;
let peerConnection = null;

const config = {
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
};

// 初始化媒体流
export async function initLocalStream(video = false) {
  try {
    localStream = await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: video,
    });
    return localStream;
  } catch (err) {
    console.error('获取本地媒体失败:', err);
    throw err;
  }
}

// 控制麦克风开关
export function toggleAudio(micOn) {
  if (localStream) {
    localStream.getAudioTracks().forEach(track => track.enabled = micOn);
  }
}

// 控制摄像头开关
export function toggleVideo(cameraOn) {
  if (localStream) {
    localStream.getVideoTracks().forEach(track => track.enabled = cameraOn);
  }
}

// 创建 Peer 连接
export function createPeerConnection({ onTrack, onIceCandidate }) {
  peerConnection = new RTCPeerConnection(config);

  localStream.getTracks().forEach(track => {
    peerConnection.addTrack(track, localStream);
  });

  // 处理远程流
  peerConnection.ontrack = event => {
    if (onTrack) onTrack(event.streams[0]);
  };

  // 处理 ICE 候选
  peerConnection.onicecandidate = event => {
    if (event.candidate && onIceCandidate) {
      onIceCandidate(event.candidate);
    }
  };

  return peerConnection;
}

// 发起通话
export async function createOffer() {
  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);
  return offer;
}

// 接收 offer 并回复 answer
export async function handleOffer(offer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  const answer = await peerConnection.createAnswer();
  await peerConnection.setLocalDescription(answer);
  return answer;
}

// 接收 answer
export async function handleAnswer(answer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
}

// 添加 ICE 候选
export function addIceCandidate(candidate) {
  peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
}

// 挂断通话
export function closeConnection() {
  if (peerConnection) {
    peerConnection.close();
    peerConnection = null;
  }
  if (localStream) {
    localStream.getTracks().forEach(track => track.stop());
    localStream = null;
  }
}

// 默认导出
export default {
  initLocalStream,
  toggleAudio,
  toggleVideo,
  createPeerConnection,
  createOffer,
  handleOffer,
  handleAnswer,
  addIceCandidate,
  closeConnection,
};
